package com.example.myapplication2;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

public class RemoteServiceActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView text;
    private ServiceConnection conn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_remote_service);
        text = findViewById(R.id.RemoteServiceText);
        findViewById(R.id.BindRemoteService).setOnClickListener(this);
        findViewById(R.id.UnBindRemoteService).setOnClickListener(this);
        findViewById(R.id.SendRemoteService).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.BindRemoteService:
                System.out.println("绑定服务");
                if (conn==null) {
                    conn = new ServiceConnection() {
                        //连接
                        @Override
                        public void onServiceConnected(ComponentName name, IBinder service) {

                        }
                        //断开
                        @Override
                        public void onServiceDisconnected(ComponentName name) {

                        }
                    };
                    Intent intent = new Intent("RemoteService");
                    bindService(intent, conn, Context.BIND_AUTO_CREATE);
                    Toast.makeText(this,"服务绑定成功", Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(this,"服务已成功", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.UnBindRemoteService:
                Toast.makeText(this,"解绑服务", Toast.LENGTH_SHORT).show();
                if (conn!=null){
                    unbindService(conn);
                    conn=null;
                    Toast.makeText(this,"服务解绑", Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(this,"服务无连接", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.SendRemoteService:
                Toast.makeText(this,"发送远程数据", Toast.LENGTH_SHORT).show();
                String s = text.getText().toString();

                break;
        }
    }
}
